$(document).ready(function() {
    prepareBehaviour();

    validateForm();

    //initPhotoUploader();
    //initVideoUploader();

    $("#confirm_dialog").dialog({
        modal: true,
        autoOpen: false,
        resizable: false,
        draggable: false
    })
});

$(window).load(function() {
    var left_height = $(".gi_left").height();
    var right_height = $(".gi_right").height();
    if (left_height < right_height) {
        $(".gi_left").height(right_height);
    }
});

function moreRem() {
    var count = $(".rem_no").length + 1;
    var customer_name = $("#customer_name option:selected").text();
    var customer_id = $("#customer_name").val();
    if (customer_id > 0) {
        var content = '<tr>' +
                '<td class="rem_no">' +
                count +
                '</td>' +
                '<td>' +
                '<span>' + customer_name + '</span>' +
                '<input type="hidden" name="rem_customers[]" readonly="true" value="' + customer_id + '"/>' +
                '</td>' +
                '<td>' +
                '<input type="text" class="rem_date entertext" placeholder="datetime" name="rem_dates[]"/>' +
                '</td>' +
                '<td>' +
                '<input type="text" class="entertext" placeholder="USD" name="rem_amounts[]"/>' +
                '</td>' +
                '<td>' +
                '<input type="text" class="entertext" placeholder="text" name="rem_remarks[]"/>' +
                '</td>' +
                '<td width="4%">' +
                '<a href="javascript:void(0)" onclick="deleteRemmitanceRow(event)">' +
                '<img src="' + base_url + '/public/images/delete.gif"/>' +
                '</a>' +
                '</td>'
        '</tr>';
        $("#tbl_remittances tbody").append(content);
        $(".rem_date").datepicker({
            dateFormat: 'dd/mm/yy'
        });
    } else {
        alert("Please choose customer");
    }
}

function moreService() {
    var content = $("#new_service tbody").html();
    $("#tbl_services tbody").append(content);
    var count = $("#tbl_services .service_no").length;
    $("#tbl_services .service_no").last().text(count);

    $(".datetime").datetimepicker({
        timeFormat: 'HH:mm'
    });


}

function deleteUploadFile(event, file_name, id, service_type) {
    $.post(base_url + "/service/delete-upload-file", {file_name: file_name, id: id, service_type: service_type}, function(resp) {
        $(event.target).parent().parent().remove();
    });
}

function getUploader(browser_button, container) {
    var uploader = new plupload.Uploader({
        runtimes: 'gears,html5,flash,silverlight,browserplus',
        browse_button: browser_button,
        container: container,
        max_file_size: '10mb',
        chunk_size: '1mb',
        require: 'chunks',
        url: base_url + '/service/plupload/id/' + ref_no,
        flash_swf_url: base_url + '/public/js/plupload/plupload.flash.swf',
        silverlight_xap_url: base_url + '/public/js/plupload/plupload.silverlight.xap',
        filters: [
            {title: "Image files", extensions: "jpg,gif,png,doc,docx,xlsx,xls,pdf"}
        ]
    });
    return uploader;
}

function parseStringToTimestamp(value) {
    if (!value) {
        return "";
    }

    value = $.trim(value);
    var token = value.split(" ");
    if (token.length != 2) {
        return 0;
    }
    var date = $.trim(token[0]);
    var tokenDate = date.split("/");
    var day = tokenDate[0];
    var month = tokenDate[1];
    var year = tokenDate[2];

    var time = $.trim(token[1]);
    var tokenTime = time.split(":");
    var hour = tokenTime[0];
    var min = tokenTime[1];

    var t = new Date(year, month, day);
    t.setHours(hour);
    t.setMinutes(min);
    return t.getTime();
}

function validateForm() {
    $.validator.addMethod("requireSelect", function(value, element, arg) {
        return value != -1;
    }, "Please choose this field");

    $.validator.addMethod('greater', function(value, el, param) {
        if ($(param).val() == "" || $("#ata").val() == "") {
            return true;
        }

        return parseStringToTimestamp($("#ata").val()) < parseStringToTimestamp($(param).val());
    }, "ATA must before ATS");

    $("#general_info").validate({
        rules: {
            'customer_name': {requireSelect: true},
            'vessel': {required: true},
            'gtr': {
                number: true
            },
            'quantity': {
                number: true
            },
            'ata': {greater: "#ats"},
            'net_weight': {number: true},
            'gross_weight': {number: true},
            'total_cargo_loaded_last_24h': {number: true},
            'total_cargo_loaded_uptodate': {number: true},
            'total_cargo_discharged_last_24h': {number: true},
            'total_cargo_discharged_uptodate': {number: true},
            'bags_no': {number: true}
        }
    });
}

function checkFileSize(event) {
    var target = event.target;
    var file = target.files[0];
    if (file) {
        if (file.size > 1024 * 2) {
            alert("File is too large");
            $(target).replaceWith($(target).clone(true));
        }
    }
}

function initPhotoUploader() {
    var photo_uploader = getUploader('add_photo', 'wrap_upload_photo');
    photo_uploader.init();

    photo_uploader.bind("BeforeUpload", function(up, file) {
        $("#upload-photo-progress").css("display", "block");
    });

    photo_uploader.bind("FilesAdded", function(up, file) {
        photo_uploader.start();
    });

    photo_uploader.bind('FileUploaded', function(up, files, resp) {
        var result = $.parseJSON(resp.response);

        var file_name = result.file_name;
        var splits = file_name.split(".");
        var file_extension = splits[splits.length - 1];
        var file_type = 'word';
        switch (file_extension) {
            case 'jpg':
            case 'png':
            case 'gif':
                file_type = 'bmp';
                break;
            case 'xlsx':
            case 'xls':
                file_type = 'excel';
                break;
            case 'pdf':
                file_type = 'pdf';
                break;
        }
        var file_path = result.path;

        var content = '<div>';
        content += '<img src="' + upload_url + file_path + '" style="padding:10px 0px;max-width:300px; max-height: 70px" />';
        content += '<div>';
        content += '<input type="text" name="photo_desc[]"/>';
        content += '</div>';
        content += "<input type='hidden' name='photos[]' value='" + file_path + "'/>";
        content += " <a href='javascript:void(0)' class='delete-file' onclick='deleteUploadFile(event, \"" + file_path + "\")'>";
        content += "<img src='" + base_url + "/public/images/delete.gif'>";
        content += "</a>";
        content += '</div>';

        $("#mask-new-photo").append(content);
        $(".ui-progressbar").css("display", "none");
    });

    photo_uploader.bind('UploadProgress', function(up, file) {
        $("#upload-photo-progress").progressbar({
            value: file.percent
        });
    });
}

function prepareBehaviour() {
    $("#quantity").change(function() {
        var number = $(this).val();

    })
    $("#purpose_of_call").change(function() {
        var purpose = $(this).val();
        if (purpose == 'Loading') {
            $("#wrap-cargo-operations").show();
            $("#wrap_discharged_cargo").hide();
            $("#wrap_loaded_cargo").show();
        } else if (purpose == 'Discharging') {
            $("#wrap-cargo-operations").show();
            $("#wrap_discharged_cargo").show();
            $("#wrap_loaded_cargo").hide();
        } else if (purpose == 'Crew change') {
            $("#wrap-crew-service").show();
            $("#wrap-daily-photos").hide();
            $("#wrap-cargo-operations").hide();
            $("#wrap-dunnage").hide();
        } else if (purpose == 'Dunnage') {
            $("#wrap-crew-service").hide();
            $("#wrap-daily-photos").show();
            $("#wrap-cargo-operations").hide();
            $("#wrap-dunnage").show();
        }

    });

    $(".datetime").datetimepicker({
        dateFormat: 'dd/mm/yy'
    });
}

function initVideoUploader() {
    var photo_uploader = getUploader('add_document', 'wrap_upload_document');
    photo_uploader.init();

    photo_uploader.bind("BeforeUpload", function(up, file) {
        $("#upload-document-progress").css("display", "block");
    });

    photo_uploader.bind("FilesAdded", function(up, file) {
        photo_uploader.start();
    });

    photo_uploader.bind('FileUploaded', function(up, files, resp) {
        var result = $.parseJSON(resp.response);

        var file_name = result.file_name;
        var splits = file_name.split(".");
        var file_extension = splits[splits.length - 1];
        var file_type = 'word';
        switch (file_extension) {
            case 'jpg':
            case 'png':
            case 'gif':
                file_type = 'bmp';
                break;
            case 'xlsx':
            case 'xls':
                file_type = 'excel';
                break;
            case 'pdf':
                file_type = 'pdf';
                break;
        }
        var file_path = result.path;

        var content = '<div class="' + file_type + ' file-new">';
        content += '<span>';
        content += file_name;
        content += '</span>';
        content += "<input type='hidden' name='documents[]' value='" + file_path + "'/>";
        content += " <a href='javascript:void(0)' class='delete-file' onclick='deleteUploadFile(event, \"" + file_path + "\")'>";
        content += "<img src='" + base_url + "/public/images/delete.gif'>";
        content += "</a>";
        content += '</div>';

        $("#mask-new-document").append(content);
        $(".ui-progressbar").css("display", "none");
    });

    photo_uploader.bind('UploadProgress', function(up, file) {
        $("#upload-document-progress").progressbar({
            value: file.percent
        });
    });
}

function deleteServiceRow(event, id) {
    if (id) {
        $("#confirm_dialog").dialog("open");
        $("#confirm_dialog").dialog({
            buttons: {
                "Yes": function() {
                    $.post(base_url + '/service/delete-service-detail', {id: id});
                    $(this).dialog("close");
                    var target = event.target;
                    var parent = $(target).parent().parent().parent();
                    var current_no = parseInt(parent.find(".service_no").text());
                    parent.remove();
                    $("#tbl_services .service_no").each(function() {
                        var no = parseInt($(this).text());
                        if (no > current_no) {
                            $(this).text(no - 1);
                        }
                    });
                },
                "No": function() {
                    $(this).dialog("close");
                }
            }
        });
    } else {
        var target = event.target;
        var parent = $(target).parent().parent().parent();
        var current_no = parseInt(parent.find(".service_no").text());
        parent.remove();
        $("#tbl_services .service_no").each(function() {
            var no = parseInt($(this).text());
            if (no > current_no) {
                $(this).text(no - 1);
            }
        });
    }

}

function deleteRemmitanceRow(event, id) {
    if (id) {
        $("#confirm_dialog").dialog("open");
        $("#confirm_dialog").dialog({
            buttons: {
                "Yes": function() {
                    $.post(base_url + '/service/delete-remittance', {id: id});
                    $(this).dialog("close");
                    var target = event.target;
                    var parent = $(target).parent().parent().parent();
                    var current_no = parseInt(parent.find(".rem_no").text());
                    parent.remove();
                    $(".rem_no").each(function() {
                        var no = parseInt($(this).text());
                        if (no > current_no) {
                            $(this).text(no - 1);
                        }
                    });
                },
                "No": function() {
                    $(this).dialog("close");
                }
            }
        });
    } else {
        var target = event.target;
        var parent = $(target).parent().parent().parent();
        var current_no = parseInt(parent.find(".rem_no").text());
        parent.remove();
        $(".rem_no").each(function() {
            var no = parseInt($(this).text());
            if (no > current_no) {
                $(this).text(no - 1);
            }
        });
    }
}

function rwmb_update_datetime_picker()
{
    var $ = jQuery;

    $('.rwmb-datetime').each(function()
    {
        var $this = $(this),
                options = $this.data('options');

        options.onSelect = function()
        {
            var currentId = $this.attr('id');
            var hiddenId = '#' + currentId + '_hidden';
            $(hiddenId).val(Math.round($this.datetimepicker("getDate").getTime() / 1000));

        };
        $this.siblings('.ui-datepicker-append').remove();         // Remove appended text
        $this.removeClass('hasDatepicker').datetimepicker(options);
    });
}

function deleteArrivalPhoto(obj, id) {
    $.post(base_url + "/service/deletevesselonarrival", {
        "id": id
    }, function(data) {
        if (data == true) {
            $(obj).parent().remove();
        } else {
            alert("Can't delete image");
        }

    }, "json");
}

function deleteDeparturePhoto(obj, id) {
    $.post(base_url + "/service/deletevesselondeparture", {
        "id": id
    }, function(data) {
        if (data == true) {
            $(obj).parent().remove();
        } else {
            alert("Can't delete image");
        }
    }, "json");
}